import { BaseBody } from "./entity/body_base";
import sdk from '../index';
import { ComType } from "../tool/component";
import pos_component from "../../component/pos_component";
import { Icard } from "../tool/Icard";
import base_component from "../../component/base_component";
import rpg_component from "../../component/rpg_component";
import enemy from "./entity/enemy";
import { BattleArea } from "./battleArea";
import player from "./entity/player";
import client_component from "../../component/client_component";
import { ClientAction } from "../../shared/api_bot/IMassage";
import { Attribute_base } from "../../shared/face/enums";
export class wordMap {
    id: string = sdk.tool.common.uuid;
    name: string = '测试世界';
    enemyCfg:string = 'test';
    /**
     * 是否刷怪
     */
    isCreateEnemy: boolean = true;
    /**
     * 地图难度
     */
    difficulty: string = 'D';
    cellMap: Map<string, wordCell> = new Map();
    constructor() {

    }

    init() {

    }
    join_body(unit: BaseBody, create: BaseBody) {
        let cell = this.checkPos(unit);
        cell.join(create);
    }
    getRadomCell() {
        let pos = `${sdk.tool.common.random(0, 1000)}_${sdk.tool.common.random(0, 1000)}`;
        let cell = this.cellMap.get(pos);
        if (!cell) {
            cell = new wordCell(pos);
            this.cellMap.set(pos, cell);
        }
        return cell;
    }
    // 探索-随机当前的附近一格
    explore(unit: BaseBody) {
        let com_pos = (unit.getComponent(ComType.位置) as pos_component);
        let cell = this.checkPos(unit);
        let pos = cell.pos;
        let pos_list = pos.split('_');
        let x = parseInt(pos_list[0]);
        let y = parseInt(pos_list[1]);
        let new_x = x + sdk.tool.common.random(-1, 1);
        let new_y = y + sdk.tool.common.random(-1, 1);
        let new_pos = `${new_x}_${new_y}`;
        let new_cell = this.cellMap.get(new_pos);
        if (!new_cell) {
            new_cell = new wordCell(new_pos);
            this.cellMap.set(new_pos, new_cell);
        }
        cell.leave(unit);
        new_cell.join(unit);
        com_pos._cell = new_cell;
        return new_cell;
    }
    // 移动-移动到指定位置
    // pos 为上下左右
    move(unit: BaseBody, pos: string) {
        let cell = this.checkPos(unit);
        let com_pos = (unit.getComponent(ComType.位置) as pos_component);
        let pos_list = cell.pos.split('_');
        let x = parseInt(pos_list[0]);
        let y = parseInt(pos_list[1]);
        if (pos == '上') {
            y--;
        }
        if (pos == '下') {
            y++;
        }
        if (pos == '左') {
            x--;
        }
        if (pos == '右') {
            x++;
        }
        let new_pos = `${x}_${y}`;
        let new_cell = this.cellMap.get(new_pos);
        if (!new_cell) {
            new_cell = new wordCell(new_pos);
            this.cellMap.set(new_pos, new_cell);
        }
        cell.leave(unit);
        new_cell.join(unit);
        com_pos._cell = new_cell;
        return new_cell;
    }
    checkPos(unit: BaseBody) {
        let pos = (unit.getComponent(ComType.位置) as pos_component);
        if (!pos._map) {
            pos._map = this;
        }
        if (pos._map.id != this.id) {
            // 地图ID不匹配，说明切换了地图，需要清除旧引用并设置新引用
            if (pos._cell) {
                pos._cell.leave(unit);
                pos._cell = undefined;
            }
            pos._map = this;
        }
        if (!pos._cell) {
            pos._cell = this.getRadomCell();
            pos._cell.join(unit);
        }
        return pos._cell;
    }
    client_getPosition(unit: BaseBody) {
        let card = sdk.tool.card.create();
        card.title(`🌏${this.name}`);
        let cell = this.checkPos(unit);
        if(this.isCreateEnemy){
            if(cell.unitMap.length < 2) {
                cell.createEnemy(this.enemyCfg,2 - cell.unitMap.length);
            }
        }
        
        const [x, y] = cell.pos.split('_');
        card.l(`📍坐标[${x},${y}]`);
        card.merge(cell.getCellInfo());
        return card;
    }
    createBattleAll(unit: BaseBody) {
        let cell = this.checkPos(unit);
        return cell.createBattleAll(unit);
    }
}
export class wordCell {
    pos: string;//x_y
    unitMap: BaseBody[] = [];
    lastEnemyCreateTime: number = 0; // 上次刷怪时间戳
    constructor(pos: string) {
        this.pos = pos;
    }
    createEnemy(table:string,count:number = 1) {
        const currentTime = Date.now();
        const fiveMinutes = 5 * 60 * 1000; // 5分钟的毫秒数
        
        // 检查是否可以刷怪：时间为0或者距离上次刷怪超过5分钟
        if ((currentTime - this.lastEnemyCreateTime) >= fiveMinutes) {
            // 在刷怪前清空已死亡的单位
            this.clearDeadUnits();
            
            for(let i = 0; i < count; i++) {
                let _enemy = new enemy();
                _enemy.randomConfig(table);
                this.join(_enemy);
            }
            // 更新刷怪时间戳
            this.lastEnemyCreateTime = currentTime;
        }
    }
    join(unit: BaseBody) {
        if (!this.unitMap.some(u => u.id === unit.id && u.constructor.name == unit.constructor.name)) {
            this.unitMap.push(unit);
        } else {
            debugger;
        }
    }
    createBattleAll(unit: BaseBody) {
        let battle = sdk.rpg.create();
        let team = { a: 0, b: 0, players: [] as player[] };
        for (let i = 0; i < this.unitMap.length; i++) {
            let _unit = this.unitMap[i];
            let com_rpg = _unit.getComponent(ComType.rpg) as rpg_component;
            if (com_rpg.isDie()) {
                continue;
            }
            if (_unit instanceof player) {
                team.players.push(_unit as player);
            }
            if (_unit.id == unit.id) {
                battle.addUnit(_unit, true);
                team.a++;
            } else {
                battle.addUnit(_unit, false);
                team.b++;
            }
        }
        if (team.a == 0 || team.b == 0) {
            let msg = '[当前位置]:发起战斗失败,没有敌人或已死亡';
            for (let i = 0; i < team.players.length; i++) {
                let com_client = team.players[i].getComponent(ComType.client) as client_component;
                com_client.client_text(msg);
            }
            return null;
        }
        return battle;
    }
    leave(unit: BaseBody) {
        const index = this.unitMap.findIndex(u => u.id === unit.id);
        if (index !== -1) {
            this.unitMap.splice(index, 1);
        } else {
            debugger
        }
    }
    getCellInfo() {
        let card = sdk.tool.card.create();
        card.title('🔎位置单位');
        for (let i = 0; i < this.unitMap.length; i++) {
            let com_base = this.unitMap[i].getComponent(ComType.base) as base_component;
            let com_rpg = this.unitMap[i].getComponent(ComType.rpg) as rpg_component;
            
            let maxHp = com_rpg.getAttribute(Attribute_base.最大生命值);
            let hpPercent = Math.round((com_rpg.hp_now / maxHp) * 100);
            let lifeStr = `♥${hpPercent}%`;
            if(hpPercent == 100 || hpPercent == 0){
                lifeStr = '';
            }
            let idx = `[${i}]`;
            if (com_rpg.isDie()) {
                idx = '💀';
            }
            card.l(`${idx}Lv.${com_rpg.level}${com_base.emoji}${com_base.nickName}${lifeStr}`);
        }
        return card;
    }
    getCellByIndex(index:number){
        return this.unitMap[index];
    }
    
    // 清空已死亡的单位
    clearDeadUnits() {
        for (let i = this.unitMap.length - 1; i >= 0; i--) {
            const unit = this.unitMap[i];
            const com_rpg = unit.getComponent(ComType.rpg) as rpg_component;
            if (com_rpg.isDie()) {
                this.unitMap.splice(i, 1);
            }
        }
    }
}
